package com.hellpro.lolbox.home.shank;

import android.Manifest;
import android.content.Context;
import android.content.pm.PackageManager;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.location.Location;
import android.location.LocationManager;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import com.hellpro.lolbox.R;
import com.hellpro.lolbox.config.UrlConfigs;
import com.hellpro.lolbox.utils.OkHttpClientUtils;
import com.hellpro.lolbox.utils.ToastShowCenter;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;


public class Shank extends AppCompatActivity {


    private SensorManager manager;
    private Bb bb;
    private boolean isOpen = false;
    private LocationManager locationManager;
    private Location location;
    private Location location1;
    private TextView textView;
    private Toolbar toolbar;


    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView( R.layout.activity_shank);
        textView = (TextView) findViewById(R.id.weizhi);
        toolbar = (Toolbar) findViewById(R.id.shakeeee);

        initView();

    }

    public void initView() {
        toolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            int i = checkSelfPermission(Manifest.permission.VIBRATE);
            String[] ss = new String[]{Manifest.permission.VIBRATE};
            if (i != PackageManager.PERMISSION_GRANTED) {
                ActivityCompat.requestPermissions(Shank.this, ss, 1);
            }
        }

        //quanx
        String[] ss = new String[]{Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION};
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            int i = checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION);
            int i1 = checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION);
            if (i != PackageManager.PERMISSION_GRANTED && i1 != PackageManager.PERMISSION_GRANTED) {
                ActivityCompat.requestPermissions(this, ss, 0);
              return;
            }
        }
        checkLocaton();


        if (isOpen) {
            bb = new Bb();
            manager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
            Sensor defaultSensor = manager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
            manager.registerListener(bb, defaultSensor, SensorManager.SENSOR_DELAY_NORMAL);

        }


    }

    class Bb implements SensorEventListener {

        @Override
        public void onSensorChanged(SensorEvent event) {
            int type = event.sensor.getType();
            float[] values = event.values;
            float x = values[0];
            float y = values[1];
            float z = values[2];
            if (type == Sensor.TYPE_ACCELEROMETER) {
                int value = 15;
                if (x >= value || x <= -value || y >= value || y <= -value || z >= value || z <= -value) {
                    Toast.makeText(Shank.this, "地址更新啦~~~", Toast.LENGTH_SHORT).show();


                        double latitude = location.getLatitude();
                        double longitude = location.getLongitude();
                    String locationURL = getLocationURL(latitude, longitude);

                    getLocation(locationURL);
                }
            }
        }

        @Override
        public void onAccuracyChanged(Sensor sensor, int accuracy) {

        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (manager != null) {
            manager.unregisterListener(bb);
        }
    }



    private void checkLocaton() {
        locationManager =  (LocationManager) getApplicationContext().getSystemService(Context.LOCATION_SERVICE);
        String networkProvider = LocationManager.NETWORK_PROVIDER;
        location =  locationManager.getLastKnownLocation(networkProvider);


        boolean providerEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);


        if (providerEnabled) {
            isOpen = true;
            ToastShowCenter.centerToast(Shank.this, "定位服务已经打开");


            if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {

                return;
            }

        } else {
            ToastShowCenter.centerToast(Shank.this, "请打开定位服务");

            isOpen = false;
        }


    }


    //得到地址的url
    private String getLocationURL(double latitude, double longitude) {
        StringBuffer sb = new StringBuffer(UrlConfigs.INTERFACE_LOCATION);
        sb.append("location=").append(latitude).append(",").append(longitude).append("&output=json&pois=1");
        Log.i("aa", sb.toString());
        return sb.toString();
    }

    private void getLocation(final String path) {

        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    String stringFromURL = OkHttpClientUtils.getStringFromURL(Shank.this, path, null);
                    try {
                        JSONObject jsonObject = new JSONObject(stringFromURL);
                        JSONObject result = jsonObject.getJSONObject("result");
                        final String formatted_address = result.getString("formatted_address");
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                 textView.setText("位置："+formatted_address);
                            }
                        });

                    } catch (JSONException e) {
                        e.printStackTrace();
                    }

                } catch (IOException e) {
                    e.printStackTrace();
                }

            }
        }).start();

    }


}
